package com.isure.audio;

/**
 * @author LeiYan
 * @describe
 * @date 2017/7/18
 * @contact email:907238552@qq.com
 */

public class SpeexUtils {
    public static int readInt(final byte[] data, final int offset) {
        /*
		 * no 0xff on the last one to keep the sign
		 */
        return (data[offset] & 0xff) | ((data[offset + 1] & 0xff) << 8) | ((data[offset + 2] & 0xff) << 16) | (data[offset + 3] << 24);
    }

    public static long readLong(final byte[] data, final int offset) {
		/*
		 * no 0xff on the last one to keep the sign
		 */
        return (data[offset] & 0xff) | ((data[offset + 1] & 0xff) << 8) | ((data[offset + 2] & 0xff) << 16)
                | ((data[offset + 3] & 0xff) << 24) | ((data[offset + 4] & 0xff) << 32) | ((data[offset + 5] & 0xff) << 40)
                | ((data[offset + 6] & 0xff) << 48) | (data[offset + 7] << 56);
    }

    public static int readShort(final byte[] data, final int offset) {
		/*
		 * no 0xff on the last one to keep the sign
		 */
        return (data[offset] & 0xff) | (data[offset + 1] << 8);
    }

    /**
     * Reads the header packet.
     *
     * <pre>
     *  0 -  7: speex_string: "Speex   "
     *  8 - 27: speex_version: "speex-1.0"
     * 28 - 31: speex_version_id: 1
     * 32 - 35: header_size: 80
     * 36 - 39: rate
     * 40 - 43: mode: 0=narrowband, 1=wb, 2=uwb
     * 44 - 47: mode_bitstream_version: 4
     * 48 - 51: nb_channels
     * 52 - 55: bitrate: -1
     * 56 - 59: frame_size: 160
     * 60 - 63: vbr
     * 64 - 67: frames_per_packet
     * 68 - 71: extra_headers: 0
     * 72 - 75: reserved1
     * 76 - 79: reserved2
     * </pre>
     *
     * @param packet
     * @param offset
     * @param bytes
     * @return
     * @throws Exception
     */
    public static  boolean readSpeexHeader(final byte[] packet, final int offset, final int bytes, boolean init) throws Exception {
        if (bytes != 80) {
            System.out.println("Oooops");
            return false;
        }
        if (!"Speex   ".equals(new String(packet, offset, 8))) {
            return false;
        }
        int mode = packet[40 + offset] & 0xFF;
        int sampleRate = readInt(packet, offset + 36);
        int channels = readInt(packet, offset + 48);
        int nframes = readInt(packet, offset + 64);
        int frameSize = readInt(packet, offset + 56);
        System.out.println("mode=" + mode + " sampleRate==" + sampleRate + " channels=" + channels + "nframes=" + nframes + "framesize="
                + frameSize);
//        initializeAndroidAudio(sampleRate);

        if (init) {
            // return speexDecoder.init(mode, sampleRate, channels, enhanced);
            return true;
        } else {
            return true;
        }
    }
}
